package com.czk.protocol.http;

import com.czk.framework.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/14 17:11
 */
public class HttpClient {
    public String send(String hostname, Integer port, Invocation invocation) throws IOException {
        URL url = new URL("http", hostname, port, "/");
        // 代开连接
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        // 设置请求方法
        httpURLConnection.setRequestMethod("POST");
        // 输出
        httpURLConnection.setDoOutput(true);
        // 拿到输出流
        OutputStream outputStream = httpURLConnection.getOutputStream();
        // 装饰者，对象输出流
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        // 输出对象
        objectOutputStream.writeObject(invocation);
        // 拿到输入流
        InputStream inputStream = httpURLConnection.getInputStream();
        String string = IOUtils.toString(inputStream);
        // 关闭流
        objectOutputStream.close();
        outputStream.close();
        return string;


    }
}
